import { useEffect, useState } from "react";

const GameList = () => {

  const [games, setGames] = useState([]);

  const loadData = () => {
    fetch(`${process.env.PUBLIC_URL}/games`)
      .then(response => response.json())
      .then(data => setGames(data));
  };
  
  useEffect(() => {
    const intervalId = setInterval(() => {
      loadData();
    }, 5000);
    loadData();

    return () => clearInterval(intervalId);
  }, []);

  return (
    <div className="games">
      <h1>Active Games</h1>
      <table className="tbl-games">
        <thead>
          <tr>
            <th>Player</th>
            <th>Seed</th>
          </tr>
        </thead>
        <tbody>
          {games.map((x, idx) => 
            <tr key={idx}>
              <td><a className="game-link" href={`${process.env.PUBLIC_URL}/game?key=${x.key}`}>{x.name}</a></td>
              <td className="seed">{x.seed}</td>
            </tr>)}
        </tbody>
      </table>
    </div>
  );
}

export default GameList;
